package parser

import (
	"github.com/fatih/color"
	"github.com/hashicorp/hcl/v2"
	"github.com/ihaiker/tfwrapper/internal/config"
	"github.com/ihaiker/tfwrapper/internal/errors"
	"github.com/ihaiker/tfwrapper/internal/util"
	"github.com/sirupsen/logrus"
)

func Parser(version string, flags config.Flags) (wrapper *config.Wrapper, diags hcl.Diagnostics) {
	wrapper = new(config.Wrapper)
	if wrapper.Config, diags = parseWrapperConfig(version, flags); util.HasErrors(diags) {
		return
	}
	if diags = versionConstraintCheck(&wrapper.Config.Running); util.HasErrors(diags) {
		return
	}

	stack, runInStackDir, err := getStack(*wrapper.Config)
	if err != nil {
		diags = errors.Diagnostics("Get stack", errors.WithStackTrace(err))
		return
	}
	wrapper.IsRunInStackDir = runInStackDir

	logrus.Infof("active stack %s, source dir is %s",
		color.HiGreenString(stack.Name), util.Color(color.FgHiGreen, stack.Source))

	if wrapper.Stack, diags = parseStackSourceConfig(*stack, *wrapper.Config, flags); util.HasErrors(diags) {
		return
	}

	if !wrapper.IsRunInStackDir {
		wrapper.RunInModuleName = determineWhichModuleIsRunning(wrapper)
	}

	return
}
